package com.sl.au.controller;

import java.io.File;
import java.io.FileInputStream;

import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.BusinesssellerAuthentication;
import com.sl.au.entity.BusinesssellerBaseInfo;
import com.sl.au.entity.Evaluate;
import com.sl.au.entity.Option;
import com.sl.au.entity.User;
import com.sl.au.service.BusinesssellerAuthenticationService;
import com.sl.au.service.BusinesssellerBaseInfoService;
import com.sl.au.service.BussessllerbaseinfoExcelloadService;
import com.sl.au.service.EvaluateService;
import com.sl.au.service.OptionService;
import com.sl.au.service.UserService;
/*
 * 批量导入Excel
 */
import com.sl.utils.MsgHelper;

@RestController
@RequestMapping(value = "/ui/bussinessbaseinfoExcelBulkload")
public class BussessllerbaseinfoExcelloadController extends BaseController {

	@Autowired
	BussessllerbaseinfoExcelloadService bussessllerbaseinfoExcelloadService;
	@Autowired
	private BusinesssellerBaseInfoService businesssellerBaseInfoService;
	@Autowired
	private UserService userService;
	@Autowired
	private OptionService optionService;
	@Autowired
	private BusinesssellerAuthenticationService businesssellerAuthenticationService;
	@Autowired
	private EvaluateService evaluateService;

	@RequestMapping(value = "/saveBussinessInfo", method = RequestMethod.POST)
	public MsgHelper saveBussinessInfo(@RequestParam(value = "file", required = false) MultipartFile file) {
		if (isRightFile(file)) {
			// 将文件上传到指定的磁盘中
			String excelPath = this.getUploadFilePath(this.fileUploadPath, "excel/bussinessBatch", file);
			// 从磁盘中读取文件信息并上传到数据库中
			excelPath = this.fileUploadPath + excelPath;

			try {
				Workbook workbook = null;
				String fileName = file.getOriginalFilename();
				if (fileName.endsWith(".xls")) {// 处理低版本
					workbook = new HSSFWorkbook(new FileInputStream(new File(excelPath)));
				}
				if (fileName.endsWith(".xlsx")) {// 处理高版本
					workbook = new XSSFWorkbook(new FileInputStream(new File(excelPath)));
				}
				Sheet sheet = workbook.getSheetAt(0);
				// List<BusinesssellerBaseInfo> list = new ArrayList<>();
				// List<User> users = new ArrayList<>();
				for (int i = 1; i < sheet.getLastRowNum(); i++) {// 遍历每一行
					Row row = sheet.getRow(i);
					// 商户名称即用户名称
					User user = new User();
					if (userService.findByName(row.getCell(0).getStringCellValue())) {
						BusinesssellerBaseInfo b = new BusinesssellerBaseInfo();
						b.setShopName(row.getCell(0).getStringCellValue());
						b.setShopAdress(row.getCell(1).getStringCellValue());
						b.setManagementRange(row.getCell(2).getStringCellValue());
						b.setLongitude(row.getCell(3).getNumericCellValue());
						b.setLatitude(row.getCell(4).getNumericCellValue());
						b.setAreaMeasure(row.getCell(5).getNumericCellValue());
						b.setSignPerson(row.getCell(6).getStringCellValue());
						b.setCleaningPerson(row.getCell(7).getStringCellValue());
						b.setMemo(row.getCell(8).getStringCellValue());
						// list.add(b);
						user.setName(b.getShopName());

						// users.add(user);

						userService.getRepository().save(user);
						b.setManagementPerson(user);
						List<Option> options = optionService.getRepository().findByGroupAndTitle("信息状态", "初始化");
						b.setInfoState(options.get(0));
						b.setBussinessLevel(user.getUserLevel());
						businesssellerBaseInfoService.getRepository().save(b);

						BusinesssellerAuthentication au = new BusinesssellerAuthentication();
						au.setManagementPerson(user);
						au.setBusinesssellerBaseInfo(b);
						au.setInfoState(options.get(0));
						businesssellerAuthenticationService.getRepository().save(au);

						Evaluate evaluate = new Evaluate();
						evaluate.setBusinesssellerBaseInfo(b);
						evaluateService.getRepository().save(evaluate);
					}

				}
				// businesssellerBaseInfoService.getRepository().save(list);

			} catch (Exception e) {
				e.printStackTrace();

			}

		}
		return MsgHelper.success();

	}
	@RequestMapping(value = "/saveBussinessInfoWithPicture", method = RequestMethod.POST)
	public MsgHelper saveBussinessInfoWithPicture(@RequestParam(value = "filepic", required = false) MultipartFile[] file) {
		for(int i=0;i<file.length;i++){
			if (isRightImgFile(file[i])) {
				if (file[i].getOriginalFilename() != null && !"".equals(file[i].getOriginalFilename())) {
					// 注意路径的构建
					String name=file[i].getOriginalFilename();
					if(name.contains("/")){
						String[] sp=name.split("/");
						name =sp[sp.length-1];
					}
					if(name.contains(".")){
						name=name.substring(0, name.lastIndexOf("."));
					}
					
					String url = getUploadFilePath(this.fileUploadPath, "img/Businessseller", file[i]);
					this.businesssellerBaseInfoService.savepicture(url, name);
				}
			}else{
				continue;
			}
		}
		return MsgHelper.success();
	}
	private boolean isRightImgFile(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		return fileName != null && !"".equals(fileName) && (fileName.endsWith(".jpg") || fileName.endsWith(".gif")|| fileName.endsWith(".ico")|| fileName.endsWith(".png"));
	}
	private boolean isRightFile(MultipartFile file) {
		String fileName = file.getOriginalFilename();
		return fileName != null && !"".equals(fileName) && (fileName.endsWith(".xlsx") || fileName.endsWith(".xls"));
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {

		ModelAndView modelAndView = this.createLayoutView("importExcel/import");

		return modelAndView;
	}

}
